import React from 'react';
import Redirect from 'umi/redirect';
import pathToRegexp from 'path-to-regexp';
import { connect } from 'dva';

const getRouteAuthority = (path, routeData) => {
  let authorities;
  routeData.forEach(route => {
    // match prefix
    if (pathToRegexp(`${route.path}(.*)`).test(path)) {
      authorities = route.authority || authorities;
      // get children authority recursively
      if (route.routes) {
        authorities = getRouteAuthority(path, route.routes) || authorities;
      }
    }
  });
  return authorities;
};

function AuthComponent({ children, location, routerData, authorities, authority }) {
  // console.log(location, authorities, authority)
  // int转为string
  let authoritiesStr = authorities ? authorities.map(item => item + '') : authorities;
  if (!authority) {
    // 没有传入authority：菜单鉴权
    // 登陆页、刷新时（会在菜单数据未组织好之前先触发一次）、403
    if (!routerData || routerData.length === 0 || routerData.some(item => item.path === '/login'
      || location.pathname === '/exception/403')) {
      return typeof children === 'undefined' ? null : children;
    }
    // 请求地址非配置路由，去触发404吧
    if (!routerData.some(item => item.path === location.pathname)) {
      return typeof children === 'undefined' ? null : children;
    }
    let routeAuthority = getRouteAuthority(location.pathname, routerData);
    let isIncludes = authoritiesStr.includes(routeAuthority);
    if (!isIncludes) {
      // 无权限
      return <Redirect to="/exception/403" />;
    }
    return typeof children === 'undefined' ? null : children;
  } else {
    // 传入authority：页面控件鉴权
    if (authority.every(item => authoritiesStr.includes(item))) {
      return typeof children === 'undefined' ? null : children;
    }
    return null;
  }
}

export default connect(({ menu: menuModel, login: loginModel }) => ({
  routerData: menuModel.routerData,
  status: loginModel.status,
  authorities: loginModel.authority,
}))(AuthComponent);
